package com.le.tester.javaThink.fifth.chapter24_ConcurrentProgramming;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.LongStream.iterate;
import static java.util.stream.LongStream.rangeClosed;

/**
 * createTime：2021/8/17 13:58
 * description：并行的寻找质数
 */
public class ParallelPrime {
    static final int COUNT = 100_000;

    //是否为质子数
    public static boolean isPrime(long n) {
        //math.sqrt,开平方根，并且四舍五入
        return rangeClosed(2, (long) Math.sqrt(n)).noneMatch(i -> n % i == 0);
    }

    public static void main(String[] args) throws IOException {
        //Timer timer = new Timer();
        LocalDateTime startTime = LocalDateTime.now();
        List<String> primes = iterate(2, i -> i + 1)
                .parallel()
                //调用isPrime，为true的进行add
                .filter(ParallelPrime::isPrime)
                .limit(COUNT)
                .mapToObj(Long::toString)
                .collect(Collectors.toList());
        LocalDateTime endTime = LocalDateTime.now();
        int duration = endTime.getSecond() - startTime.getSecond();
        System.out.println("duration time is " + duration + " second");
        //Files.write(Paths.get("primes.txt"),primes, StandardOpenOption.CREATE);
        System.out.println(primes);
    }

    //获取持续的时间段
    public static int getDuration(LocalDateTime startTime, LocalDateTime endTime) {
        return endTime.getSecond() - startTime.getSecond();
    }
}
